package com.tools;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;
import java.util.zip.GZIPOutputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.entity.AbstractHttpEntity;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import android.content.ContentResolver;
import android.content.Context;
import android.location.Location;
import android.net.wifi.WifiManager;
import android.os.Handler;

public class HttpInterface {
	// public static String mmscUrl = "http://www.baidu.com/";
	// public static String mmsProxy = "10.0.0.172"; // 代理地址
	// public static String mmsProt = "80"; // 代理端口号
	// private HttpListenerInterface listenerInterface;
	public static final int	HTTP_POST_METHOD	= 1;
	public static final int	HTTP_GET_METHOD		= 2;
	
	public HttpInterface(Handler handler) {
		this.handler = handler;
	}
	
	// public interface HttpListenerInterface
	// {
	// /***********************************************************
	// * @author sun.huang MSN:jxhuanghua@yahoo.com.cn
	// * @version time：2011-12-1 下午03:49:20
	// * @param progress
	// * @TODO 进度值，百分比
	// ***********************************************************/
	// public void progressChanage(float progress);
	// }
	
	// public void setListener(HttpListenerInterface listenerInterface)
	// {
	// this.listenerInterface = listenerInterface;
	// }
	//	
	/***********************************************************
	 * @author sun.huang MSN:jxhuanghua@yahoo.com.cn
	 * @version time：2011-11-15 下午07:07:46
	 * @param soTimeoutSec
	 * @param url
	 * @param method
	 * @param params
	 *        POST 方式链接，发送的内容 List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("to", to));
	 * @param proxyHost
	 *        代理IP地址 如果不使用代理，则传null
	 * @param proxyPort
	 *        代理服务器端口号
	 * @return
	 * @throws HttpThrowable
	 * @TODO 使用方法:InputStream in = entity.getContent() 使用后请销毁 entity.consumeContent();
	 ***********************************************************/
	// public HttpEntity httpConnection(int soTimeoutSec, String url, int method, List<NameValuePair> nameValuePair, String proxyHost, int proxyPort) throws HttpThrowable {
	// HttpClient client = createHttpClient(soTimeoutSec);
	// HttpEntity entity = null;
	// try {
	// if (nameValuePair != null) {
	// entity = new UrlEncodedFormEntity(nameValuePair);
	// }
	// } catch (UnsupportedEncodingException e) {
	// throw new HttpThrowable(HttpThrowable.POST_DATA, e);
	// }
	// return httpConnection(client, url, method, entity, proxyHost, proxyPort);
	// }
	
	public HttpEntity httpPostConnection(HttpClient client, String url, HttpEntity entity) throws HttpThrowable {
		
		URI hostUrl = null;
		HttpRequest req = null;
		HttpHost target = null;
		HttpResponse response = null;
		try {
			hostUrl = new URI(url);
			HttpPost post = new HttpPost(url);
			post.setEntity(entity);
			req = post;
			target = new HttpHost(hostUrl.getHost(), hostUrl.getPort(), HttpHost.DEFAULT_SCHEME_NAME);
			HttpParams params = client.getParams();
			req.setParams(params);
			response = client.execute(target, req);
			StatusLine status = response.getStatusLine();
			MyLog.i(url + " StatusLine is " + status);
			if (status.getStatusCode() != 200) { // HTTP 200 is success.
				throw new HttpThrowable(HttpThrowable.STATUS_CODE_ERROR, "HTTP error: " + status.getReasonPhrase());
			}
			HttpEntity reuleEntity = response.getEntity();
			
			if (reuleEntity != null) {
				return reuleEntity;
			} else {
				throw new HttpThrowable(HttpThrowable.INTENT_ERROR, "intent error, response entity is null.");
			}
		} catch (Exception e) {
			MyLog.e(e);
		}
		return null;
		
	}
	
	//	
	public HttpEntity httpGetConnection(HttpClient client, String url) throws HttpThrowable {
		
		URI hostUrl = null;
		HttpRequest req = null;
		HttpHost target = null;
		HttpResponse response = null;
		HttpEntity reuleEntity = null;
		try {
			hostUrl = new URI(url);
			req = new HttpGet(url);
			target = new HttpHost(hostUrl.getHost(), hostUrl.getPort(), HttpHost.DEFAULT_SCHEME_NAME);
			HttpParams params = client.getParams();
			req.setParams(params);
			
			response = client.execute(target, req);
			StatusLine status = response.getStatusLine();
			MyLog.i(url + " StatusLine is " + status);
			if (status.getStatusCode() != 200) { // HTTP 200 is success.
				throw new HttpThrowable(HttpThrowable.STATUS_CODE_ERROR, "HTTP error: " + status.getReasonPhrase());
			}
			reuleEntity = response.getEntity();
		} catch (Exception es) {
			throw new HttpThrowable(HttpThrowable.INTENT_ERROR, es);
		}	
		return reuleEntity;
	}
	
	/***********************************************************
	 * @author sun.huang MSN:jxhuanghua@yahoo.com.cn
	 * @version time：2011-11-14 下午03:07:08
	 * @param context
	 * @param soTimeoutSec
	 * @return
	 * @TODO 创建网络接口
	 ***********************************************************/
	public HttpClient createHttpClient(int soTimeoutSec) {
		HttpParams httpParams;
		httpParams = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(httpParams, soTimeoutSec * 1000);
		HttpConnectionParams.setSoTimeout(httpParams, soTimeoutSec * 1000);
		HttpClientParams.setRedirecting(httpParams, true);
		HttpClient client = new DefaultHttpClient(httpParams);
		return client;
	}
	
	/***********************************************************
	 * @author sun.huang MSN:jxhuanghua@yahoo.com.cn
	 * @version time：2011-10-21 上午11:24:53
	 * @param context
	 * @return
	 * @TODO Wifi是否可用 true:可用 false:不可用
	 ***********************************************************/
	public boolean isWifiEnabled(Context context) {
		try {
			boolean ret = false;
			if (context != null) {
				WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
				if (wifi.getWifiState() == WifiManager.WIFI_STATE_ENABLED) {
					ret = true;
				}
			}
			return ret;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		
	}
	
	Handler				handler;
	static UserLocation	userLocation;
	
	//	
	public Location getLocation(final Context context) {
		if (userLocation == null) {
			userLocation = new UserLocation(context, handler);
			
		}
		handler.post(new Runnable() {
			@Override
			public void run() {
				userLocation.startLocationListener();
			}
		});
		return userLocation.getLastKnownLocation();
	}
	
	//	
	// public void stopGetLocation()
	// {
	// if (userLocation != null)
	// {
	// userLocation.stopLocationListenter();
	// userLocation = null;
	// }
	// }
	//	
	/***
	 * 压缩数据
	 */
	public static AbstractHttpEntity getCompressedEntity(byte data[], ContentResolver resolver) throws IOException {
		AbstractHttpEntity entity;
		if (data.length < getMinGzipSize(resolver)) {
			entity = new ByteArrayEntity(data);
		} else {
			ByteArrayOutputStream arr = new ByteArrayOutputStream();
			OutputStream zipper = new GZIPOutputStream(arr);
			zipper.write(data);
			zipper.close();
			entity = new ByteArrayEntity(arr.toByteArray());
			entity.setContentEncoding("gzip");
		}
		return entity;
	}
	
	/***
	 * 取得最小压缩数据大小
	 */
	public static long getMinGzipSize(ContentResolver resolver) {
		return 256;
	}
}
